﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Media.Imaging;
using System.Xml.Linq;
using FreeGoo.GameEngine;

namespace FreeGoo.LevelClasses
{
    public class Campaign
    {
        private string _bitmapName;

        public Campaign(CampaignHandler campaignHandler)
        {
            CampaignHandler = campaignHandler;
            Levels = new ObservableCollection<Level>();
        }

        public Campaign(CampaignHandler campaignHandler, string fileName)
            : this(campaignHandler)
        {
            LoadFromFile(fileName);
        }

        public CampaignHandler CampaignHandler { get; private set; }
        public Engine Engine { get { return CampaignHandler.Engine; } }
        public string Title { get; set; }
        public string Description { get; set; }
        public string FileName { get; private set; }
        public BitmapImage BitmapImage { get; protected set; }
        public string BitmapName
        {
            get
            {
                return _bitmapName;
            }

            set
            {
                _bitmapName = value;
                if (!String.IsNullOrEmpty(_bitmapName))
                {
                    BitmapImage = new BitmapImage();
                    #if !SILVERLIGHT
                    BitmapImage.BeginInit();
                    #endif
                    BitmapImage.UriSource = new Uri(new Uri(FileName), _bitmapName);
                    #if !SILVERLIGHT
                    BitmapImage.EndInit();
                    #endif
                }
                else
                {
                    BitmapImage = null;
                }
            }
        }

        public ObservableCollection<Level> Levels { get; private set; }

        protected void LoadFromFile(string fileName)
        {
            FileName = fileName;
            XElement root = XDocument.Load(fileName).Root;

            Title = root.Attribute("Title").Value;
            if (root.Element("Description") != null)
            {
                Description = root.Element("Description").Value;
            }

            if (root.Attribute("ImageFileName") != null)
            {
                BitmapName = root.Attribute("ImageFileName").Value;
            }

            Levels.Clear();

            Uri baseUri = new Uri(Path.GetFullPath(FileName));
            foreach (XElement element in root.Element("Levels").Elements("Level"))
            {
                Uri uri = new Uri(baseUri, element.Attribute("FileName").Value);
                Levels.Add(new Level(this, uri.AbsolutePath));
            }
        }
    }
}

